<?php
// 本类由系统自动生成，仅供测试用途
namespace Api\Controller;
use Think\Controller;

class PublicController extends Controller {

    public $redis;
    public $visitor ;
    public $t_session;
    
    //构造函数
    public function _initialize(){
	    //php 判断http还是https
    	$http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://'; 
    	//所有图片路径
	    define(__DATAURL__, $http_type.$_SERVER['SERVER_NAME'].__DATA__.'/');
	    define(__PUBLICURL__, $http_type.$_SERVER['SERVER_NAME'].__PUBLIC__.'/');
	    define(__HTTP__, $http_type);
        define('CHARSET', "utf-8");

        //链接redis
        $this->redis = new \Redis();
        $this->redis->connect('127.0.0.1',6379);

        //接受t_session
        $this->t_session = $_REQUEST['t_session'];

    }


    /**
     * 查找二级分类下的所有子分类id，用逗号拼接
     * @param int $id
     * @return string
     */
    public function catid_tree($id=2){
		$Category = M('category');
		$list=$Category->where("tid=".$id)->order('sort desc,id asc')->select();
		//dump($list);exit;
		$cidstr='';
		foreach($list as $v){
			$json[]=$v['id'];
			$num=$Category->where("tid=".$v['id'])->field('id')->count();
			if($num>0){
				$json[]=$this->catid_tree($v['id']);
			}
		}
		$cidstr.=implode(',',$json);
		return $cidstr;		
	}

    /**
     * 一次性查出所有的分类
     * @param int $id
     * @return array
     */
	public function cat_tree($id=2){
		$Category = M('category');
		$list=$Category->where("tid=".$id)->field('id,tid,name')->order('sort desc,id asc')->select();
		//echo '<pre>';print_r($list);exit;
		foreach($list as $v){
			$num = $Category->where("tid=".$v['id'])->count();
			$subclass=array();
			if($num>0)
			{
				$subclass=$this->cat_tree($v['id']);
			}
			$json[]=array(
				'id' => $v['id'] ,
				'name' => $v['name'] ,
				'num' => $num ,
				'subclass' => $subclass,
			);
		}
		return $json;		
	}


    /**
     * 导航部分  查找父级分类
     * @param $categoryID
     * @return array
     */
    function getAllFcateIds($categoryID)
    {
        //初始化ID数组
        $array[] = $categoryID;
         
        do
        {
            $ids = '';
            $where['id'] = array('in',$categoryID);
            $cate = M('category')->where($where)->field('id,tid,name')->select();
            foreach ($cate as $v)
            {
                $array[] = $v['tid'];
                $ids .= ',' . $v['tid'];
            }
            $ids = substr($ids, 1, strlen($ids));
            $categoryID = $ids;
        }
        while (!empty($cate));
        foreach ($array as $key=>$va){
           $cates[] = M('category')->where('id='.$va)->field('id,tid,name')->find();
		   $cates[$key]['name']=str_replace('（系统分类，不要删除）','',$cates[$key]['name']);
        }
        array_pop($cates);
        $ca=array_reverse($cates);
        return $ca; //返回数组
    }
    
	public function ispc($val){
		$app = M('admin_app');
		$val=$app->getField('id');
		$url = $app->where('id='.$val)->field('ispcshop,end_time,name,pcnav_color,ahover_color')->find();
		if($url['end_time'] > time()){
			return $url;
		}else{
			return 0;
		}
    }

    /** Send a Header
    *
    * @return  void
    *
    * @auther Doujia
    * Sep 26, 2011
    */
    public function json_header()
    {
        header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
        header("Content-type:text/plain;charset=" . CHARSET, true);
    }

    /**
     * Make a successfully message
     *
     * @param   mixed   $retval
     * @param   string  $msg
     *
     * @auther Doujia
     * Sep 26, 2011
     */
    public function json_result($retval = '', $msg = '', $jqremote = false)
    {
        if (! empty($msg)) {
            $msg = $msg;
        }
        $this->json_header();
        $json = ecm_json_encode(array('done' => true, 'msg' => $msg, 'retval' => $retval));
        if ($jqremote === false) {
            $jqremote = isset($_GET['jsoncallback']) ? trim($_GET['jsoncallback']) : false;
        }
        if ($jqremote) {
            $json = $jqremote . '(' . $json . ')';
        }
        echo $json;
        exit;
    }

    /**
     * Make a error message by JSON format
     *
     * @param   string  $msg
     * @return  void
     *
     * @auther Doujia
     * Sep 26, 2011
     */
    public function json_error($msg = '', $retval = null, $jqremote = false)
    {
        //begin add by tongxuefen 2011-04-21 ajax 没有登录或登录超时
        if ($msg == 'login_please') {
            echo '<script language="javascript"> window.top.history.go(0);</script>';
            return;
        }
        //end add
        if (! empty($msg)) {
            $msg = $msg;
        }
        $result = array('done' => false, 'msg' => $msg);
        if( $msg == '请登录' or $msg == 'login_please'){
            $result = array('done' => false,  'reLogin' => true, 'msg' => $msg);
        }

        if (isset($retval))
            $result['retval'] = $retval;
        $this->json_header();
        $json = ecm_json_encode($result);
        if ($jqremote === false) {
            $jqremote = isset($_GET['jsoncallback']) ? trim($_GET['jsoncallback']) : false;
        }
        if ($jqremote) {
            $json = $jqremote . '(' . $json . ')';
        }
        echo $json;
        exit;
    }

    /**
     * 设置缓存的方法
     * @param $name
     * @param $data
     * @author tiedong
     * @date 2017-01-17
     */
    public function get_cache($name,$data )
    {
        $cache = S(array(
                'type'=>'Redis',
                'host'=>'127.0.0.1',
                'port'=>'6379',
                'prefix'=>'think',
                'expire'=>60
            )
        ); //缓存初始化
        $cache->$name =$data;
        if (empty(S("$name"))) {
            $res = "数据为空！";
        } else {
            $res = S("$name");
        }
        return $res;
    }

    /*
       去除HTNL标签
    */
    public function html_entity($array){
        foreach ($array as $key => $value) {
            $array[$key]['content'] = strip_tags(html_entity_decode($value['content']));
        }
        return $array;
    }

    //购物车添加。删除检测公共方法
    public function check_cart($pid){
        $product_model = M('product');
        //检查产品是否存在或删除
        $check_info = $product_model->where('id='.intval($pid).' AND del=0 AND is_down=0')->find();
        if (!$check_info) {
            $check = $product_model->where('id='.intval($pid).' AND del=0 AND is_down=1')->find();
            return array('status'=>0,'err'=>'('.$check['name'].')商品不存在或已下架.');
        }
        return array('status'=>1);
    }

    //检查库存
    public function check_num($pid,$num){
        $product_model = M('product');
        //检查产品是否存在或删除
        $check_info = $product_model->where('id='.intval($pid).' AND del=0 AND is_down=0')->find();
        if (intval($check_info['num'])<=$num) {
            return array('status'=>0,'err'=>'('.$check_info['name'].')库存不足.');
        }
        return array('status'=>1);
    }

    /*
	*
	* 图片上传的公共方法
	*  $file 文件数据流 $exts 文件类型 $path 子目录名称
	*/
    public function upload_images($file,$exts,$path){
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =  10*1024*1024 ;// 设置附件上传大小2M
        $upload->exts      =  $exts;// 设置附件上传类型
        $upload->rootPath  =  './Data/UploadFiles/'; // 设置附件上传根目录
        $upload->savePath  =  ''; // 设置附件上传（子）目录
        $upload->saveName = time().mt_rand(100000,999999); //文件名称创建时间戳+随机数
        $upload->autoSub  = true; //自动使用子目录保存上传文件 默认为true
        $upload->subName  = $path; //子目录创建方式，采用数组或者字符串方式定义
        // 上传文件
        $info = $upload->uploadOne($file);
        if(!$info) {// 上传错误提示错误信息
            return $upload->getError();
        }else{// 上传成功 获取上传文件信息
            //return 'UploadFiles/'.$file['savepath'].$file['savename'];
            return $info;
        }
    }

    /**
     * 保存用户信息到redis
     * @author tiedong
     * @param  $data
     */
    public function setUserInfo($data= array(),$sessionKey)
    {
        foreach ($data as $dataKey => $dataVal) {
            $data[$dataKey] = serialize($dataVal);
        }
        $returnData = $this->redis->hMSet($sessionKey, $data);
        $time = 60*60*24*30;
        $this->setTimeout($sessionKey, $time);
        return $returnData;
    }

    /**
     * 获取用户的信息
     * @author tiedong
     * @date
     * @param  $key
     * @param  $unserialize
     */
    public function getUserInfo($key,$unserialize = true)
    {
        $data = $this->redis->hGetAll($key);
        if ($unserialize) {
            foreach ($data as $dataKey => $dataVal) {
                $data[$dataKey] = unserialize($dataVal);
            }
        }
        return $data;
    }

    /**
     * 获取单的
     */
    public function get($key)
    {
        $data = $this->getUserInfo("$this->t_session",$unserialize = true);
        return $data[$key];
    }

    /**
     * 设置超时
     * @param string $key
     * @param int $timeToLive
     */
    public function setTimeout($key, $timeToLive)
    {
        return $this->redis->setTimeout($key, $timeToLive);
    }


}